package com.ruoyi.zsyh.controller.applet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.AuthBaiduUtils;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.zsyh.domain.Area;
import com.ruoyi.zsyh.domain.SysDtArea;
import com.ruoyi.zsyh.domain.ZsyhUserAddress;
import com.ruoyi.zsyh.service.ISysDtAreaService;
import com.ruoyi.zsyh.service.IZsyhUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户地址管理Controller
 * 
 * @author zhangkm
 * @date 2022-2-21
 */
@Controller
@RequestMapping("/applet/zsyh/userAddress")
public class ZsyhUserAddressAppletController extends BaseController
{


    @Autowired
    private IZsyhUserAddressService zsyhUserAddressService;

    @Autowired
    private ISysDtAreaService sysDtAreaService;

    @Autowired
    private RedisUtil redisUtils;



    /**
     * 添加收货地址
     * @return
     * @throws Exception
     */
    @RepeatSubmit
    @RequestMapping("/saveUserAddress")
    @ResponseBody
    public AjaxResult saveUserAddress(String userId, String name, String phone, String pCode, String pName,String cCode, String cName, String aCode, String aName, String address)throws Exception
    {
        ZsyhUserAddress userAddress = new ZsyhUserAddress();
        userAddress.setId(IdWorker.getId());
        userAddress.setUserId(userId);
        userAddress.setAddressDetail(address);
        userAddress.setAddressPrivinceName(pName);
        userAddress.setAddressProvince(pCode);
        userAddress.setAddressCity(cCode);
        userAddress.setAddressCityName(cName);
        userAddress.setAddressDistrict(aCode);
        userAddress.setAddressDistrictName(aName);
        userAddress.setAddressName(name);
        userAddress.setAddressPhone(phone);

        ZsyhUserAddress appletAddress = new ZsyhUserAddress();
        appletAddress.setUserId(userId);
        List<ZsyhUserAddress> list = zsyhUserAddressService.selectZsyhUserAddressList(appletAddress);
        if(list.size() == 0){
            userAddress.setIsDefault("1");
        }
        zsyhUserAddressService.insertZsyhUserAddress(userAddress);
        return success("操作成功");
    }

    /**
     *  编辑收货地址
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateUserAddress")
    @ResponseBody
    public AjaxResult updateUserAddress(String id, String name, String phone, String pCode, String pName,String cCode, String cName, String aCode, String aName, String address)throws Exception
    {
        ZsyhUserAddress userAddress = new ZsyhUserAddress();
        userAddress.setId(id);
        userAddress.setAddressDetail(address);
        userAddress.setAddressPrivinceName(pName);
        userAddress.setAddressProvince(pCode);
        userAddress.setAddressCity(cCode);
        userAddress.setAddressCityName(cName);
        userAddress.setAddressDistrict(aCode);
        userAddress.setAddressDistrictName(aName);
        userAddress.setAddressName(name);
        userAddress.setAddressPhone(phone);
        zsyhUserAddressService.updateZsyhUserAddress(userAddress);

        return success("操作成功");
    }

    /**
     *  设为默认
     * @return
     * @throws Exception
     */
    @RequestMapping("/setDefaultUserAddress")
    @ResponseBody
    public AjaxResult setDefaultUserAddress(String userId, String id)throws Exception
    {
        zsyhUserAddressService.updateSetDefaultUserAddress(userId, id);
        return success("操作成功");
    }

    /**
     * 删除收货地址
     * @return
     * @throws Exception
     */
    @RequestMapping("/delUserAddress")
    @ResponseBody
    public AjaxResult delUserAddress(String userId, String id)throws Exception
    {
        ZsyhUserAddress agentAddress = zsyhUserAddressService.selectZsyhUserAddressById(id);
        if("0".equals(agentAddress.getIsDefault())){
            zsyhUserAddressService.deleteZsyhUserAddressById(id);
        }else{
            ZsyhUserAddress userAddress = new ZsyhUserAddress();
            userAddress.setUserId(userId);
            List<ZsyhUserAddress> list = zsyhUserAddressService.selectZsyhUserAddressList(userAddress);
            if(list.size() == 1){
                return AjaxResult.error("操作失败，唯一地址无法删除");
            }else {
                String newId = "";
                for(ZsyhUserAddress a:list){
                    if(!id.equals(a.getId())){
                        newId = a.getId();
                    }
                }
                zsyhUserAddressService.deleteZsyhUserAddressById(id);//删除地址
                ZsyhUserAddress _user = new ZsyhUserAddress();
                _user.setId(newId);
                _user.setIsDefault("1");
                zsyhUserAddressService.updateZsyhUserAddress(_user);//修改第一个地址为默认地址
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 获取我的默认地址
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserDefaultAddress")
    @ResponseBody
    public AjaxResult getUserDefaultAddress(String userId)throws Exception
    {
        ZsyhUserAddress userAddress = new ZsyhUserAddress();
        userAddress.setUserId(userId);
        userAddress.setIsDefault("1");
        List<ZsyhUserAddress> list = zsyhUserAddressService.selectZsyhUserAddressList(userAddress);
        if(list.size() > 0 ){
            return AjaxResult.success("操作成功", list.get(0));
        }else{
            return AjaxResult.error("暂无默认收货地址");
        }
    }

    /**
     * 获取我的地址信息
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserAddressByUserId")
    @ResponseBody
    public AjaxResult getUserAddressByUserId(String userId)throws Exception
    {
        ZsyhUserAddress userAddress = new ZsyhUserAddress();
        userAddress.setUserId(userId);
        List<ZsyhUserAddress> list = zsyhUserAddressService.selectZsyhUserAddressList(userAddress);
        if(list.size() > 0 ){
            return AjaxResult.success("操作成功", list);
        }else{
            return AjaxResult.error("暂无收货地址");
        }
    }


    /**
     * 获取地址详情
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserAddressById")
    @ResponseBody
    public AjaxResult getUserAddressById(String id)throws Exception
    {
        return AjaxResult.success("操作成功", zsyhUserAddressService.selectZsyhUserAddressById(id));
    }


    /**
     * 地址解析
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserAddressJsonByText")
    @ResponseBody
    public AjaxResult getUserAddressJsonByText(String text)throws Exception
    {

        if(EmptyUtils.isEmpty(text)){
            return AjaxResult.error("数据不正确，找不到地址信息");
        }
        String result = AuthBaiduUtils.getAddress(text, redisUtils, 1);
        JSONObject jsonObject = JSON.parseObject(result);
        logger.info(jsonObject + "------------------------jsonObject");
        String townCode = String.valueOf(jsonObject.get("town_code"));//乡镇级别代码 第四级别
        String countyCode = String.valueOf(jsonObject.get("county_code"));//区县级别代码 第三级别
        if(EmptyUtils.isNotEmpty(townCode)){
            Map map = sysDtAreaService.getSysArea(townCode);
            if(map != null){
                jsonObject.put("province_code", map.get("pId"));
                jsonObject.put("province", map.get("pName"));
                jsonObject.put("city_code", map.get("cId"));
                jsonObject.put("city", map.get("cName"));
                jsonObject.put("county_code", map.get("aId"));
                jsonObject.put("county", map.get("aName"));
                logger.info(jsonObject + "------------------------jsonObject");
                return AjaxResult.success("操作成功",jsonObject);
            }
        }
        if(EmptyUtils.isNotEmpty(countyCode)){
            Map map = sysDtAreaService.getSysArea(countyCode);
            if(map != null){
                jsonObject.put("province_code", map.get("pId"));
                jsonObject.put("province", map.get("pName"));
                jsonObject.put("city_code", map.get("cId"));
                jsonObject.put("city", map.get("cName"));
                jsonObject.put("county_code", map.get("aId"));
                jsonObject.put("county", map.get("aName"));
                logger.info(jsonObject + "------------------------jsonObject");
                return AjaxResult.success("操作成功",jsonObject);
            }
        }
        return AjaxResult.error("数据不正确，找不到地址信息");
    }

    /**
     * 获取所有的省市县
     * @param text
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectAreaTree")
    @ResponseBody
    public AjaxResult selectAreaTree(String text)throws Exception
    {
        List<Area> areaList = sysDtAreaService.selectAreaTree();
        return AjaxResult.success("成功", areaList);
    }


}
